package com.laker.admin.text;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Formatter;
import java.util.Enumeration;

public class Demo {
    public static void main(String[] args) {
        try {
            // 获取本机的InetAddress实例
//            InetAddress ip = InetAddress.getLocalHost();
//            String ipAddress = ip.getHostAddress(); // 获取IP地址
//            System.out.println("IP Address: " + ipAddress);
//
//            // 获取网络接口对象，并遍历
//            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
//            while (interfaces.hasMoreElements()) {
//                NetworkInterface networkInterface = interfaces.nextElement();
//                byte[] mac = networkInterface.getHardwareAddress();
//                if (mac != null) {
//                    Formatter formatter = new Formatter();
//                    for (byte b : mac) {
//                        formatter.format("%02X:", b);
//                    }
//                    String macAddress = formatter.toString();
//                    macAddress = macAddress.substring(0, macAddress.length() - 1); // 移除最后一个冒号
//                    System.out.println("MAC Address: " + macAddress);
//                    formatter.close();
//                }
//            }

            // 获取所有网络接口
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();

                // 指定网络适配器
                if (networkInterface.getDisplayName().equals("VMWARE")) {

                }
                // 获取该网络接口的所有地址
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();

                    // 过滤IPv4地址
                    if (address instanceof java.net.Inet4Address) {
                        System.out.println("IPv4 address : " + address.getHostAddress());
                    }
                }

                byte[] mac = networkInterface.getHardwareAddress();
                if (mac != null) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < mac.length; i++) {
                        sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                    }
                    // 输出mac地址
                    System.out.println("MAC address : " + sb.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
